//
//  TTServiceManager.swift
//  TianTianBiTing
//
//  Created by Gox mac 2 on 2018/12/28.
//  Copyright © 2018 Gox_WallyDiao. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import HandyJSON

let TTneedSign = true
let TTneedEncrypted = true
let TTMaxRequest = 10
var TTCurrentRequestCount = 0

class TTServiceManager: NSObject {

    static let shared = TTServiceManager.init()
    private override init() {
        super.init()
        self.httpManager = TTHttpManager()
        weak var weakSelf = self

    }

    var httpManager: TTHttpManager!
    
    fileprivate var requestQueue:TTRequestQueue = TTRequestQueue()

}


//  MARK: - ###### 私有方法 ######
extension TTServiceManager {
    fileprivate func startQueue(){
        self.requestQueue.setActive(true)
        self.checkQueue()
    }
    
    fileprivate func pauseQueue()  {
        self.requestQueue.setActive(false)
    }
    
    fileprivate func checkQueue(){
        
        guard self.requestQueue.getActive() == true else {
            return
        }
        
        let model = self.requestQueue.outQueue()
        guard model != nil else {
            return
        }
        self.requestWithModel(model as! TTRequestModel)
    }

    fileprivate func getPlatform() -> String {
        return "server"
    }

    fileprivate func getVersion() -> String {
        let version = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
        return version
    }
    
    fileprivate func requestWithModel(_ requestModel:TTRequestModel){
        weak var weakSelf = self
        
        TTCurrentRequestCount += 1
        print("*******开始请求*******")
        self.request(requestModel.getUrl(), method: requestModel.getMethod(), parameters: requestModel.getparameters(), headers: requestModel.getHeaders(), { (response) in
            let response = response!
            var json = JSON(response.value ?? "")
            TTCurrentRequestCount -= 1
            print("*******请求完成：\(response)*******")
            
            weakSelf?.checkQueue()
            requestModel.resultsBlock?(json)
            requestModel.dataResponseBlock?(response)
        })
    }
    
    fileprivate func requestWithModelNew(_ requestModel:TTRequestModel){
        weak var weakSelf = self
        
        TTCurrentRequestCount += 1
        print("*******开始请求*******")
        self.request(requestModel.getUrl(), method: requestModel.getMethod(), parameters: requestModel.getparameters(), headers: requestModel.getHeaders(), { (response) in
            let response = response!
            var json = JSON(response.value ?? "")
            TTCurrentRequestCount -= 1
            print("*******请求完成：\(response)*******")
            
            weakSelf?.checkQueue()
            requestModel.resultsBlock?(json)
            requestModel.dataResponseBlock?(response)
        })
    }
    
    fileprivate func request(_ url: String, method:Alamofire.HTTPMethod , parameters: Parameters? , headers: HTTPHeaders? ,_ completionHandler: @escaping (Alamofire.DataResponse<Any>?) -> Void) {
        weak var weakSelf = self
        self.httpManager.performRequest(url, method: method, parameters: parameters, headers: headers, completionHandler: { (response) in
            let response = response!
            
            completionHandler(response)
            
        })
    }
    
    fileprivate func requestNew(_ url: String, method:Alamofire.HTTPMethod , parameters: Parameters? , headers: HTTPHeaders? ,_ completionHandler: @escaping (Alamofire.DataResponse<Any>?) -> Void) {
        weak var weakSelf = self
        self.httpManager.performRequest(url, method: method, parameters: parameters, headers: headers, completionHandler: { (response) in
            let response = response!
            
            completionHandler(response)
            
        })
    }
    
}

//  MARK: - ###### 公有方法 ######
extension TTServiceManager {
    func setQueueActive(active:Bool)  {
        self.requestQueue.setActive(active)
    }
    
    //  MARK: *****请求入口
    func request(_ url: String, method:Alamofire.HTTPMethod , parameters: Parameters? , headers: HTTPHeaders? ,result: @escaping (JSON) -> Void) {
        
        let requestModel:TTRequestModel = TTRequestModel.init(url: url, method: method, parameters: parameters, headers: headers, resultsBlock: result)
        
        guard TTCurrentRequestCount < TTMaxRequest else {
            self.requestQueue.intoQueue(requestModel)
            return
        }
        
        guard self.requestQueue.getActive() else {
            self.requestQueue.intoQueue(requestModel)
            return
        }
        self.requestWithModel(requestModel)
    }
    
    func requestNew(_ url: String, method:Alamofire.HTTPMethod , parameters: Parameters? , headers: HTTPHeaders? ,result: @escaping (JSON) -> Void) {
        
        let requestModel:TTRequestModel = TTRequestModel.init(url: url, method: method, parameters: parameters, headers: headers, resultsBlock: result)
        
        self.requestWithModelNew(requestModel)
    }
}
